package com.justnow;

/**
 * 此方法存在的问题是，如果存在大数的情况下，测试用例不通过！
 */
public class TwoNumberSumLikedList {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int l1Number = listToInt(l1);
        int l2Number = listToInt(l2);
        int sum = l1Number + l2Number;
        ListNode retHead = intToList(sum);
        return retHead;
    }

    //将链表转换为数组
    public int listToInt(ListNode list) {
        int number = 0;
        int times = 1;
        while(list != null) {
            number += (list.val*times);
            times *= 10;
            list = list.next;
        }
        return number;
    }

    //将数组转换为链表
    public ListNode intToList(int number) {
        int times = 10;
        ListNode head = new ListNode(-1);
        if (number == 0)
            return new ListNode(0);
        ListNode current = head;
        while(number > 0) {
            int temp = number % times;
            ListNode tempNode = new ListNode(temp);
/*
            tempNode.next = head.next;
            head.next = tempNode;
*/
            //应该用尾插入法
            current.next = tempNode;
            current = current.next;
            number /= times;
        }
        return head.next;
    }

    public static void main(String[] args) {
        TwoNumberSumLikedList sum = new TwoNumberSumLikedList();
        ListNode L1node1 = new ListNode(2);
        ListNode L1node2 = new ListNode(4);
        ListNode L1node3 = new ListNode(3);
        L1node1.next = L1node2;
        L1node2.next = L1node3;
        ListNode L2node1 = new ListNode(5);
        ListNode L2node2 = new ListNode(6);
        ListNode L2node3 = new ListNode(4);
        L2node1.next = L2node2;
        L2node2.next = L2node3;
        ListNode listNode = sum.addTwoNumbers(L1node1, L2node1);
    }
}

